import { getNewCartGoodsAPI, mergeLocalCartAPI, getCartListAPI, insertCartAPI, deleteCartAPI, updateCartAPI, checkAllCartAPI } from '@/api'
// 购物车模块
export default {
  namespaced: true, // 开启命名空间
  state () {
    return {
      // 购物车列表
      list: []
    }
  },
  mutations: {
    // 加入购物车
    SET_CARTLIST (state, payload) {
      // 判断是否已经添加过商品
      const targetObj = state.list.find(obj => obj.skuId === payload.skuId)
      if (targetObj) {
        targetObj.count += payload.count
      } else {
        state.list.unshift(payload)
      }
    },
    // 更新购物车状态
    UPDATE_CART (state, goods) {
      const targetObj = state.list[goods.index]
      for (const key in goods) {
        if (key !== 'index') {
          targetObj[key] = goods[key]
        }
      }
    },
    // 删除
    DELETE_CART (state, obj) {
      const index = state.list.findIndex(item => item.skuId === obj.skuId)
      state.list.splice(index, 1)
    },
    // 更新购物车
    SET_LIST (state, payload) {
      state.list = payload
    }
  },
  actions: {
    // 加入购物车
    async insertCartActions (store, goods) {
      const { token } = store.rootState.user.profile
      if (token) {
      // 已登录
        await insertCartAPI({
          skuId: goods.skuId,
          count: goods.count
        })
        // 调用线上购物车列表
        store.dispatch('getCartListActions')
      } else {
        // 未登录
        store.commit('SET_CARTLIST', goods)
      }
    },
    // 获取每个商品最新状态（库存）
    findCartActions  (store) {
      const newArr = store.state.list.map(async goodsObj => {
        if (goodsObj.skuId) {
          return await getNewCartGoodsAPI(goodsObj.skuId)
        }
      })
      Promise.all(newArr).then(res => {
        if (res.result) {
          const resultArr = res.map(obj => obj.result)
          resultArr.forEach((item, index) => {
            store.commit('UPDATE_CART', {
              ...item,
              index: index
            })
          })
        }
      })
    },
    // 删除功能
    async deleteCartActions (store, obj) {
      const { token } = store.rootState.user.profile
      if (token) {
        // 已登录删除
        await deleteCartAPI([obj.skuId])
        // 调用线上购物车列表
        store.dispatch('getCartListActions')
      } else {
        // 未登录删除
        store.commit('DELETE_CART', obj)
      }
    },
    // 合并购物车
    async mergeLocalCartActions (store) {
      const newArr = store.state.list.map(obj => ({
        skuId: obj.skuId,
        selected: obj.check,
        count: obj.count
      }))
      const res = await mergeLocalCartAPI(newArr)
      return res // 返回一个promims
    },
    // 获取-线上购物列表
    async getCartListActions (store) {
      const res = await getCartListAPI()
      store.commit('SET_LIST', res.result)
    },
    // 更新单个商品(属性值)
    async updateCartActions (store, goods) {
      // goods { skuId , bool }
      const { token } = store.rootState.user.profile
      if (token) {
        // 登录
        await updateCartAPI(goods)
        // 调用线上购物车列表
        store.dispatch('getCartListActions')
      } else {
        // 未登录
        goods.index = store.state.list.findIndex(item => item.skuId === goods.skuId)
        store.commit('UPDATE_CART', goods)
      }
    },
    // 全选
    async checkAllCartActions (store, bool) {
      const { token } = store.rootState.user.profile
      if (token) {
        // 登录
        const idsArr = store.getters.validList.map(item => item.skuId)
        await checkAllCartAPI({
          selected: bool,
          ids: idsArr
        })
        // 调用线上购物车列表
        store.dispatch('getCartListActions')
      } else {
      // 未登录
        store.getters.validList.forEach(obj => {
          const index = store.state.list.findIndex(item => item.skuId === obj.skuId)
          store.commit('UPDATE_CART', {
            index: index,
            selected: bool
          })
        })
      }
    }
  },
  getters: {
    // 筛选符合条件的合格商品 已上架 && 库存大于1
    validList (state) {
      return state.list.filter(item => item.isEffective === true && item.stock > 0)
    },
    // 商品有效件数
    validTotal (state, getters) {
      return getters.validList.reduce((sum, goods) => {
        sum += goods.count
        return sum
      }, 0)
    },
    // 购物车商品总价
    validAmount (state, getters) {
      return getters.validList.reduce((sum, goods) => {
        sum += goods.count * goods.nowPrice
        return sum
      }, 0)
    },
    // 全选状态
    isCheckAll (state, getters) {
      return getters.validList.every(obj => obj.selected === true)
    },
    // 统计购物车商品选中状态
    isSeleMount (state, getters) {
      return getters.validList.reduce((sum, obj) => {
        if (obj.selected === true) {
          sum += obj.count
        }
        return sum
      }, 0)
    },
    // 购物车所有选中商品的总价
    isSelePrice (state, getters) {
      return getters.validList.reduce((sum, obj) => {
        if (obj.selected === true) {
          sum += obj.count * obj.nowPrice
        }
        return sum
      }, 0)
    }

  }
}
